<?php

class WxAuth{
    /**
     * @param $url
     * @return mixed
     */
    public static function getSignature($url){
        /*$timestamp = time();
        $wxnonceStr = "anystring";
        $wxticket = self::wx_get_jsapi_ticket();
        $wxOri = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", $wxticket, $wxnonceStr, $timestamp, $url);
        $wxSha1 = sha1($wxOri);
        $result['timestamp'] = $timestamp;
        $result['wxnonceStr'] = $wxnonceStr;
        $result['wxticket'] = $wxticket;
        $result['wxSha1'] = $wxSha1;*/

        $result['timestamp'] = 1498630966;
        $result['wxnonceStr'] = "anystring";
        $result['wxticket'] = "sM4AOVdWfPE4DxkXGEs8VAwOt9oraqOZppse87IiN3uy-kJF8IdU2-y6Gls_z3_nCL7DWdlff39JpAGXEs-OWw";
        $result['wxSha1'] = "d0344eda3c19450544b5b9a76f7ba1aebd35bba5";
        return $result;
    }

    /**
     * 获取jsapi的ticket
     * @return string
     */
    public static function wx_get_jsapi_ticket(){
        $ticket = "";
        do{
            if(function_exists('apc_fetch')){
                $ticket = apc_fetch('wx_ticket');
            }
            if (!empty($ticket)) {
                break;
            }
            if(function_exists('apc_fetch')){
                $token = apc_fetch('access_token');
            }
            if (empty($token)){
                $token = self::wx_get_token();
            }
            //$token = apc_store('access_token');
            if (empty($token)) {
                return 'get access token error.';
                break;
            }
            $url2 = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", $token);
            $res = file_get_contents($url2);
            $res = json_decode($res, true);
            $ticket = $res['ticket'];

            // ticket和token一样，不能频繁的访问接口来获取，在每次获取后，我们把它保存起来。
            //apc_store('wx_ticket', $ticket, 3600);
        }while(0);
        return $ticket;
    }
    /**
     * 获取令牌
     * @param $app_id
     * @param $app_secret
     * @return mixed
     */
    public static function wx_get_token() {
        $app_id = "wx13b0ce87f8202ad4";
        $app_secret = "734f4ea7dcccdd1c014907077de1df0d";
        if(function_exists('apc_fetch')){
            $token = apc_fetch('access_token');
        }else{
            $token = null;
        }
        if (!$token) {
            $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$app_id.'&secret='.$app_secret);
            $res = json_decode($res, true);
            $token = $res['access_token'];
            //apc_store('access_token', $token, 3600);
        }
        return $token;
    }
}